package com.lvchen.ui.onefunction.banner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.lvchen.R;
import com.lvchen.common.base.BaseActivity;
import com.siberiadante.titlelayoutlib.TitleBarLayout;

import java.util.List;

/**
 * bannerweb详情页
 */
public class BannerWebActivity extends BaseActivity {

    private TitleBarLayout tb_title;
    private WebView web_url;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ensureUi();
    }

    @SuppressLint("JavascriptInterface")
    private void ensureUi() {
        tb_title = (TitleBarLayout) findViewById(R.id.tb_title);
        tb_title.setIsHaveLine(false);
        tb_title.setTitle(getIntent().getStringExtra("title"));

        tb_title.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(web_url.canGoBack()){
                    web_url.goBack();
                }else{
                    onBackPressed();
                }
            }
        });

        web_url = (WebView) findViewById(R.id.web_url);

        web_url.clearCache(true);
        web_url.clearHistory();
        System.out.println("地址============"+getIntent().getStringExtra("url"));
        web_url.loadUrl(getIntent().getStringExtra("url"));
        web_url.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        web_url.getSettings().setJavaScriptEnabled(true); //设置支持Javascript
        web_url.getSettings().setDomStorageEnabled(true);
        web_url.requestFocus(); //触摸焦点起作用.如果不设置，则在点击网页文本输入框时，不能弹出软键盘及不响应其他的一些事件。

        web_url.setWebViewClient(new webViewClient());

        web_url.addJavascriptInterface(new Object(){

            @JavascriptInterface
            public void showToast() {

                myHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        web_url.goBack();
                    }
                });
            }

        },"AndroidFunction");

        web_url.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message,JsResult result){
                return super.onJsAlert(view, url, message, result);
            }
        });

    }


    class webViewClient extends WebViewClient {
        //重写shouldOverrideUrlLoading方法，使点击链接后不使用其他的浏览器打开。
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out.println("地址======="+url);
            if (url.contains("alipays://platformapi")){
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                if(resolveInfos.size() > 0){
                    startActivity( intent );
                }
            }else{
                view.loadUrl(url);
            }
            //如果不需要其他对点击链接事件的处理返回true，否则返回false
            return false;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();// 这里，继续执行ssl

        }
    }

    private Handler myHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://
                    web_url.loadUrl(getIntent().getStringExtra("url"));
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public static void goToThisActivity(Context context, String title, String url) {
        Intent intent = new Intent();
        intent.setClass(context, BannerWebActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK&&web_url.canGoBack()){
            web_url.goBack();
            return true;
        }else{
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

}
